<template>
  <div>
    <div class="filter-container" style="text-align:right">
      <el-input @keyup.enter.native="handleSearch" style="width: 200px;" class="filter-item" placeholder="用户名" v-model="queryParams.username" size="small"></el-input>
      <el-input @keyup.enter.native="handleSearch" style="width: 200px;" class="filter-item" placeholder="姓名" v-model="queryParams.name" size="small"></el-input>
      <el-input @keyup.enter.native="handleSearch" style="width: 200px;" class="filter-item" placeholder="电话" v-model="queryParams.phone" size="small"></el-input>
      <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch" class="filter-item">搜索</el-button>
      <el-button type="primary" icon="el-icon-plus" size="small" @click="handleCreate" class="filter-item">新增</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%" border size="mini">
      <el-table-column label="头像" width="80px" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.profile.avatar" style="width:30px" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="用户名"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          <el-tag close-transition v-for="item in scope.row.roles.data" :key="item.id" class="el-tag" size="mini">{{item.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="profile.name" label="姓名"></el-table-column>
      <el-table-column label="性别" width="80px" align="center">
        <template slot-scope="scope">
          <el-tag close-transition class="el-tag" size="mini" :type="scope.row.profile.gender|statusType">{{scope.row.profile.gender|statusGender}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="绑定微信" width="80px" align="center">
        <template slot-scope="scope">
          <el-tag close-transition class="el-tag" size="mini" :type="scope.row.bound_wechat|statusType">{{scope.row.bound_wechat|statusBool}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="激活" width="80px" align="center">
        <template slot-scope="scope">
          <el-tag close-transition class="el-tag" size="mini" :type="scope.row.is_active|statusType">{{scope.row.is_active|statusBool}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:right">
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="pagination.current_page" :page-size="pagination.per_page" layout="total, prev, pager, next" :total="pagination.total">
      </el-pagination>
    </div>
    <el-dialog :title="dialogMode==='create'?'新增':'修改'" :visible.sync="dialogVisible" @close="handleClose">
      <el-form ref="userInfo" :model="userInfo" :rules="rules" label-width="80px" size="small">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="userInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="profile.name">
          <el-input v-model="userInfo.profile.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userInfo.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="profile.gender">
          <el-radio-group v-model="userInfo.profile.gender">
            <el-radio :label=0>男</el-radio>
            <el-radio :label=1>女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否激活" prop="is_active">
          <el-switch v-model="userInfo.is_active"></el-switch>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-transfer v-model="userInfo.roles" :data="rolesData" :titles="['系统角色','已有角色']"></el-transfer>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="userInfo.profile.desc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import { getRoles } from 'api/role'
import { getUsers, createUser, updateUser, deleteUser } from 'api/user'
import { validatPhone } from 'utils/validate'
export default {
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validatPhone(value)) {
        callback(new Error('电话号码格式不正确'))
      } else {
        callback()
      }
    }
    return {
      tableData: null,
      pagination: {
        current_page: 1,
        per_page: 15,
        total: 0
      },
      dialogVisible: false,
      dialogMode: '',
      queryParams: {
        username: '',
        name: '',
        phone: '',
        page: 1
      },
      rolesData: [],
      userInfo: {
        id: '',
        name: '',
        phone: '',
        is_active: false,
        roles: [],
        profile: {
          name: '',
          gender: 0,
          desc: ''
        }
      },
      rules: {
        name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        'profile.name': [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          {
            required: true,
            validator: validatePhone,
            trigger: 'blur'
          }
        ],
        'profile.gender': [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        roles: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个系统角色',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    handleCurrentChange(val) {
      this.queryParams.page = val
      this._getUsers()
    },
    handleCreate() {
      this.dialogMode = 'create'
      this.dialogVisible = true
    },
    handleEdit(index, row) {
      this.dialogMode = 'edit'
      // 有嵌套层的深拷贝
      this.userInfo = JSON.parse(JSON.stringify(row))
      let roles = this.userInfo.roles.data
      this.userInfo.roles = roles.map(role => role.id)
      this.dialogVisible = true
    },
    handleDelete(index, row) {
      deleteUser(row.id).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.tableData.indexOf(row)
        this.tableData.splice(index, 1)
      })
    },
    handleSave() {
      this.$refs['userInfo'].validate(valid => {
        if (valid) {
          if (this.dialogMode === 'create') {
            // 深拷贝
            const { ...data } = this.userInfo
            delete data.id
            console.log(data)
            createUser(data).then(response => {
              this.tableData.unshift(response)
              this.dialogVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            const id = this.userInfo.id
            const { ...data } = this.userInfo
            delete data.id
            updateUser(id, data).then(response => {
              for (const item of this.tableData) {
                if (item.id === response.id) {
                  const index = this.tableData.indexOf(item)
                  this.tableData.splice(index, 1, response)
                  break
                }
              }
              this.dialogVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClose() {
      this._resetForm()
    },
    handleSearch() {
      this.queryParams.page = 1
      this._getUsers()
    },
    _getUsers() {
      getUsers(this.queryParams).then(response => {
        this.tableData = response.data
        this.pagination = response.meta.pagination
      })
    },
    _getRoles() {
      getRoles().then(response => {
        const data = response.data
        data.forEach((item, index) => {
          this.rolesData.push({
            label: item.name,
            key: item.id
          })
        })
      })
    },
    _resetForm() {
      this.$refs['userInfo'].resetFields()
      this.userInfo = {
        id: '',
        name: '',
        phone: '',
        is_active: false,
        roles: [],
        profile: {
          name: '',
          gender: 0,
          desc: ''
        }
      }
    }
  },
  created() {
    this._getUsers()
    this._getRoles()
  },
  filters: {
    statusGender(status) {
      const statusMap = {
        0: '男',
        1: '女'
      }
      return statusMap[status]
    },
    statusBool(status) {
      const statusMap = {
        true: '是',
        false: '否'
      }
      return statusMap[status]
    },
    statusType(status) {
      const statusMap = {
        true: 'success',
        false: 'danger',
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    }
  }
}
</script>

<style scoped lang="stylus">
.el-tag
  margin-right 8px
</style>
